﻿using BencodeNET.Objects;
using Furion.Extras.Admin.NET;
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net;

namespace PrivateTracker.NET.Application
{
    //[Comment("peer")]
    //[Table("tracker_peer")]
    public class Peer //: DEntityTenant
    {
        //[ForeignKey("TorrentId")]
        //public virtual Torrent torrent { get; set; }
        /// <summary>
        /// 主表外键
        /// </summary>
        [Comment("主表外键")]
        public virtual long? TorrentId { get; set; }

        [Comment("客户端标识")]
        public virtual string PeerId { get; set; }
        [Comment("Ip地址")]
        public virtual string Ip { get; set; }
        [Comment("端口")]
        public virtual int Port { get; set; }
        [Comment("上传量")]
        public virtual long DownLoaded { get; set; }
        [Comment("下载量")]
        public virtual long Uploaded { get; set; }
        /// <summary>
        /// 客户端
        /// </summary>
        [Comment("客户端")]
        public virtual string Agent { get; set; }
        //[NotMapped]
       // public IPEndPoint ClientAddress { get; private set; }
        public byte[] ToBytes()
        {
            var portBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)this.Port));
            var addressBytes = IPAddress.Parse(this.Ip).GetAddressBytes();
            var resultBytes = new byte[portBytes.Length + addressBytes.Length];
            // 根据协议规定，首部的 4 字节为 IP 地址，尾部的 2 自己为端口信息
            Array.Copy(addressBytes, resultBytes, addressBytes.Length);
            Array.Copy(portBytes, 0, resultBytes, addressBytes.Length, portBytes.Length);
            return resultBytes;
        }
        public BDictionary ToEncodedDictionary()
        {
            return new BDictionary
            {
                {TrackerConsts.PeerIdKey,new BString(PeerId)},
                {TrackerConsts.Ip,new BString(this.Ip.ToString())},
                {TrackerConsts.Port,new BNumber(this.Port)}
            };
        }
    }
}
